//
//  GAKKIFeatureCollectionView.m
//  GANGAIKit
//
//  Created by fh on 2019/11/8.
//  Copyright © 2019 cashchina. All rights reserved.
//

#import "GAKKIFeatureCollectionView.h"
#import "GAKKIConfig.h"

@interface GAKKIFeatureCollectionView () <UICollectionViewDelegate>
/// 集合视图控件
@property (nonatomic, readwrite, strong) UICollectionView *collectionView;
/// 布局配置
@property (nonatomic, readwrite, strong) GAKKIFeatureCollectionViewConfiguration *configuration;
@end

@implementation GAKKIFeatureCollectionView
#pragma mark - Life

#pragma mark - Public
/// 初始化
- (instancetype)init {
    return [self initWithConfiguration:nil];
}

/// 初始化
/// @param delegate 代理
- (instancetype)initWithGAKKIFeatureCollectionViewDelegate:(id<GAKKIFeatureCollectionViewDelegate>)delegate {
    if (self = [self initWithCustomConfigurationSettingBlock:nil collectionViewDelegate:nil]) {
        self.delegate = delegate;
    }
    return self;
}

/// 初始化
/// @param delegate 代理
/// @param settingBlock 配置回调
- (instancetype)initWithGAKKIFeatureCollectionViewDelegate:(id<GAKKIFeatureCollectionViewDelegate>)delegate customConfigurationSettingBlock:(void (^ _Nullable)(GAKKIFeatureCollectionViewConfiguration * _Nonnull))settingBlock {
    if (self = [self initWithCustomConfigurationSettingBlock:settingBlock collectionViewDelegate:nil]) {
        self.delegate = delegate;
    }
    return self;
}

/// 初始化
/// @param delegate 代理
/// @param settingBlock 配置回调
/// @param collectionViewDelegate 集合视图代理:如果制定外部代理则该类的配置文件将失效,需要代理实现流布局的协议,该参数一般置为nil
- (instancetype)initWithGAKKIFeatureCollectionViewDelegate:(id<GAKKIFeatureCollectionViewDelegate>)delegate customConfigurationSettingBlock:(void (^ _Nullable)(GAKKIFeatureCollectionViewConfiguration * _Nonnull))settingBlock collectionViewDelegate:(id<UICollectionViewDelegate> _Nullable)collectionViewDelegate {
    if (self = [self initWithCustomConfigurationSettingBlock:settingBlock collectionViewDelegate:collectionViewDelegate]) {
        self.delegate = delegate;
    }
    return self;
}

/// 初始化
/// @param configuration 配置模型
- (instancetype)initWithConfiguration:(GAKKIFeatureCollectionViewConfiguration *)configuration {
    return [self initWithConfiguration:configuration collectionViewDelegate:nil];
}

/// 初始化
/// @param configuration 配置模型
/// @param delegate 代理
- (instancetype)initWithConfiguration:(GAKKIFeatureCollectionViewConfiguration *)configuration collectionViewDelegate:(id<UICollectionViewDelegate>)delegate {
    return [self initWithCustomConfigurationSettingBlock:^(GAKKIFeatureCollectionViewConfiguration * _Nonnull settingConfiguration) {
        if (configuration) {
            settingConfiguration = configuration;
        }
    } collectionViewDelegate:delegate];
}

/// 初始化
/// @param settingBlock 配置回调
/// @param delegate 代理
- (instancetype)initWithCustomConfigurationSettingBlock:(void (^)(GAKKIFeatureCollectionViewConfiguration * _Nonnull))settingBlock collectionViewDelegate:(id<UICollectionViewDelegate>)delegate {
    __weak typeof(self) weakSelf = self;
    if (self = [super init]) {
        [self inner_baseDefaultInitSetup];
        if (settingBlock) {
            settingBlock(weakSelf.configuration);
        }
        if (delegate) {
            self.collectionView.delegate = delegate;
        }else {
            self.collectionView.delegate = self;
        }
        [self setupView];
    }
    return self;
}

/// 注册cell:这个方法需要在
/// @param cellClass cell
/// @param identifier 重用符标示
- (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier {
    if (kStringIsEmpty(identifier)) {
        NSString *cellName = NSStringFromClass(cellClass);
        [self.collectionView registerClass:[cellClass class] forCellWithReuseIdentifier:[NSString stringWithFormat:@"%@ReuserIdentify",cellName]];
        return;
    }
    [self.collectionView registerClass:[cellClass class] forCellWithReuseIdentifier:identifier];
}

#pragma mark - Overwrite
- (void)setupView {
    [self addSubview:self.collectionView];
    [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(0));
        make.left.equalTo(@(0));
        make.bottom.equalTo(@(0));
        make.right.equalTo(@(0));
    }];
}

#pragma mark - Private
- (void)inner_baseDefaultInitSetup {
    self.configuration = [GAKKIFeatureCollectionViewConfiguration configuration];
}

#pragma mark - UICollectionViewDelegateFlowLayout
// UICollectionViewCell最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return self.configuration.defaultLayoutColumnSpace;
}
// UICollectionViewCell最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.configuration.defaultLayoutLineSpace;
}
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//    //    宽度和高度的设置有一个没用（取决于滚动方向）
//    if (self.scrollDirection == UICollectionViewScrollDirectionVertical) {
//        return CGSizeMake(collectionView.bounds.size.width, 120);
//    }else {
//        return CGSizeMake(120, collectionView.bounds.size.height);
//    }
//}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (self.configuration.sectionInset.left + self.configuration.sectionInset.right > CGRectGetWidth(collectionView.frame)) {
        return UIEdgeInsetsMake(self.configuration.sectionInset.top, 0, self.configuration.sectionInset.bottom, 0);
    }
    if (self.configuration.sectionInset.top + self.configuration.sectionInset.bottom > CGRectGetHeight(collectionView.frame)) {
        return UIEdgeInsetsMake(0, self.configuration.sectionInset.left, 0, self.configuration.sectionInset.right);
    }
    return self.configuration.sectionInset;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.configuration.defaultLayoutEachColumnOrLineCountPriority == FlowLayoutDefaultLayoutEachColumnOrLineCountPriorityHigh) {
        
        if (self.configuration.scrollDirection == UICollectionViewScrollDirectionVertical) {
            CGFloat width = (CGRectGetWidth(collectionView.frame) - (self.configuration.sectionInset.left + self.configuration.sectionInset.right) - self.configuration.defaultLayoutColumnSpace * (self.configuration.defaultLayoutColumnCount - 1)) / self.configuration.defaultLayoutColumnCount;
            //Bug Fixed:解决因为浮点数精度计算误差导致布局问题-> 四舍五入保留2位小数再偏小末尾一个点
            CGFloat realWidth = (floorf(width * 1000 + 0.5))/1000 - 0.001;
            if (realWidth < 0) {
                realWidth = 0;
            }
//            return CGSizeMake(realWidth,_shouldUseDefaultLayoutItemHeight ? realWidth : self.defaultLayoutItemHeight);
            
            CGFloat handleW = realWidth/self.configuration.itemSizeWHScale;
            return CGSizeMake(realWidth,self.configuration.shouldUseDefaultLayoutItemHeight ? realWidth : (self.configuration.shouldFitItemSizeWHScale ? handleW : self.configuration.defaultLayoutItemHeight));
            
        }else {
            CGFloat height = (CGRectGetHeight(collectionView.frame) - (self.configuration.sectionInset.top + self.configuration.sectionInset.bottom) - self.configuration.defaultLayoutLineSpace * (self.configuration.defaultLayoutLineCount - 1)) / self.configuration.defaultLayoutLineCount;
            //Bug Fixed:解决因为浮点数精度计算误差导致布局问题-> 四舍五入保留2位小数再偏小末尾一个点
            CGFloat realHeight = (floorf(height * 1000 + 0.5))/1000 - 0.001;
            if (realHeight < 0) {
                realHeight = 0;
            }
//            return CGSizeMake(_shouldUseDefaultLayoutItemWidth ? realHeight : self.defaultLayoutItemWidth,realHeight);
            
            CGFloat handleH = realHeight*self.configuration.itemSizeWHScale;
            return CGSizeMake(self.configuration.shouldUseDefaultLayoutItemWidth ? realHeight : (self.configuration.shouldFitItemSizeWHScale ? handleH : self.configuration.defaultLayoutItemWidth), realHeight);
            
        }
        
    }else {
        return CGSizeMake(self.configuration.defaultLayoutItemWidth < 0 ? 0 : self.configuration.defaultLayoutItemWidth,self.configuration.defaultLayoutItemHeight < 0 ? 0 : self.configuration.defaultLayoutItemHeight);
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(0, 0); //64
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeMake(0, 0); // 20
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.delegate && [self.delegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)]) {
        [self.delegate collectionView:collectionView didSelectItemAtIndexPath:indexPath];
    }
}

#pragma mark - Setter and getter
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        UICollectionViewLayout *layout = self.configuration.collectionViewLayout;
        if (self.configuration.collectionViewLayout) {
            layout = self.configuration.collectionViewLayout;
        }else {
            layout = self.configuration.systemDefaultLayout;
        }
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
//        if (self.configuration.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
//            _collectionView.bounces = NO;
//        }
        _collectionView.backgroundColor = [UIColor whiteColor];
        
    }
    return _collectionView;
}


@end
